import axios from 'axios'
import { baseUrl } from '@/config/index'
import { ElMessage } from 'element-plus'
// 请求基地址
axios.defaults.baseURL = baseUrl
axios.interceptors.request.use((res: any) => {
  if (localStorage.getItem('session')) {
    res.headers['session'] = localStorage.getItem('session')
  }

  return res
})
// 响应拦截器--处理响应数据
axios.interceptors.response.use((res) => {
  const { data } = res
  // console.log(data)
  if ((data as any).status == 0) {
    return data
  } else {
    ElMessage.error((data as any).msg)
    return Promise.reject(data)
  }
})
// 用来发送添加数据的请求封装
export function postData(
  url: string,
  data: any,
  headers: any = {
    'Content-type': 'application/json',
  }
) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      headers,
      method: 'POST',
      data,
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
// 用来发送更新数据的请求封装
export function putData(url: string, data: any) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'PUT',
      data,
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
// 用来发送获取数据的请求封装
export function getData(url: string, params?: any) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'GET',
      params,
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
// 用来发送删除数据的请求封装
export function deleteData(url: string, params?: any) {
  return new Promise((resolve, reject) => {
    axios({
      url,
      method: 'DELETE',
      params,
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
